package com.byinsight.web.actions.util;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.byinsight.service.dto.Dimension;
import com.byinsight.web.actions.Constants;

import eg.backend.base.PermissionType;
import eg.backend.util.TimeDimension;

public class DimensionHelper {
	
	private static Map<PermissionType, String> permissionTypeStringMap;
	
	static {
		permissionTypeStringMap = new Hashtable<PermissionType, String>();
		permissionTypeStringMap.put(PermissionType.PRIVATE, "0");
		permissionTypeStringMap.put(PermissionType.PUBLIC, "1");
		permissionTypeStringMap.put(PermissionType.GROUP, "2");
	}
	
	public static StringBuffer toXml(List<Dimension> rootDimensions) {
		StringBuffer xml = new StringBuffer();
		for (Dimension root : rootDimensions) {
			xml.append("<col><type>dimension</type>");
			xml.append("<displayName>").append(root.getName()).append("</displayName>");
			xml.append("<id>").append(root.getEncodedKey()).append("</id>");
			xml.append("<dimdef>");
			xml.append("<dimension name=\"").append(root.getName()).append("\" id=\"").append(root.getEncodedKey()).append("\">");
			xml.append(toXml(root));
			xml.append("</dimension></dimdef></col>");	
		}
		System.out.println(xml);
		return xml;
	}
	
	public static StringBuffer toDimDefXml(Dimension rootDimension) {
		StringBuffer xml = new StringBuffer();
		Dimension root = rootDimension;
		xml.append("<dimension name=\"").append(root.getName()).append("\" id=\"").append(root.getEncodedKey()).append("\">");
		xml.append(toXml(root));
		xml.append("</dimension>");		
		return xml;
	}
	
	public static String tagsToXml(List<String> tags) {
		StringBuffer ret = new StringBuffer("<tags>");
		int len = tags.size();
		for (int i = 0; i < len; i++) {
			ret.append(tags.get(i));
			if (i < len - 1) {
				ret.append(" ");
			}
		}
		ret.append("</tags>");
		return ret.toString();
	}
	
	private static StringBuffer toXml(Dimension dimension) {
		StringBuffer xml = new StringBuffer();
		if(dimension == null) 
			return xml;
		xml.append("<node id=\"").append(dimension.getEncodedKey()).append("\"");
		xml.append(" name=\"").append(dimension.getName()).append("\" ");
		PermissionType permission = dimension.getPermission();
		if(permission == null) permission = PermissionType.PRIVATE;
		xml.append(Constants.DIM_PERMISSION).append("=\"").append(permissionTypeToString(permission)).append("\">");
		
		List<Dimension> children = dimension.getChildren();
		if(children != null) {
			for(Dimension child : children)
				xml.append(toXml(child));
		}
			
		xml.append("</node>");
		return xml;
	}
	
	private static String permissionTypeToString(PermissionType pt) {
		return permissionTypeStringMap.get(pt);
	}
	
	public static PermissionType stringToPermissionType(String str) {
		Iterator<PermissionType> iter = permissionTypeStringMap.keySet().iterator();
		while (iter.hasNext()) {
			PermissionType pt = iter.next();
			String ptStr = permissionTypeStringMap.get(pt);
			if (ptStr.equalsIgnoreCase(str)) {
				return pt;
			}
		}
		return null;
	}
	
//	public static Dimension toDimension(String id, String rootDimId) {
//		Dimension ret = new Dimension();
//		ret.setEncodedKey(id);
//		ret.setRootDimension(rootDimId);
//		return ret;
//	}
	
	/**
	 * 
	 * @param tag - xml tag
	 * @param value - xml text value
	 * @return
	 */
//	public static Dimension toDimensionWithTag(String tag, String value) {
//		String strId = tag.substring(Constants.DIM_PREFIX.length());
////		Long rootDimId = parseLong(strId);
////		Long id = parseLong(value);
//		return toDimension(value, strId);
//	}
	
	public static TimeDimension toTimeDimension(String text) {
		if (null == text || !text.startsWith("TIME")) {
			return null;
		}
		
		TimeDimension ret = new TimeDimension();
		text = text.substring("TIME".length());
		String[] token = text.split("-");
		if (hasToken(0, token)) {
			ret.setYear(parseInt(token[0]));
		}
		
		if (hasToken(1, token)) {
			ret.setMonth(parseInt(token[1]));
		}
		
		if (hasToken(2, token)) {
			ret.setWeek(parseInt(token[2]));
		}
		
		return ret;
	}
	
	private static boolean hasToken(int index, String[] tokens) {
		if (tokens != null && tokens.length >= index + 1 && tokens[index] != null) {
			return true;
		}
		return false;
	}
	
	private static int parseInt(String str) {
		return Integer.parseInt(str);
	}
	
	public static Dimension toDto(eg.backend.domain.Dimension dimension) {
		Dimension dto = new Dimension();
		dto.setChildPosition(dimension.getChildPosition());
		dto.setDescription(dimension.getDescription());
		dto.setEncodedKey(dimension.getEncodedKey());
		dto.setName(dimension.getName());
		dto.setOwner(dimension.getOwner());
		dto.setPosition(dimension.getPosition());
		
		Dimension root = new Dimension();
		root.setEncodedKey(dimension.getRootDimension());
		dto.setRootDimension(root);
		Dimension parent = new Dimension();
		parent.setEncodedKey(dimension.getParent());
		dto.setParent(parent);
		
		List<Dimension> children = new ArrayList<Dimension>();
		List<eg.backend.domain.Dimension> oldChildren = dimension.getTempChildren();
		if(oldChildren == null || oldChildren.size() == 0)
			oldChildren = dimension.getChildren();
		if(oldChildren != null) {
			for(eg.backend.domain.Dimension child : oldChildren) {
				children.add(toDto(child));
			}
		}
		dto.setChildren(children);
		
		return dto;
	}
	
	public static eg.backend.domain.Dimension fromDto(Dimension dto) {
		eg.backend.domain.Dimension dimension = new eg.backend.domain.Dimension();
		dimension.setChildPosition(dto.getChildPosition());
		dimension.setDescription(dto.getDescription());
		String key = dto.getEncodedKey();
		if(key != null) {
			try {
				long id = Long.parseLong(key);
				if(id < 0)
					key = null;
			} catch (Throwable e) {}
		}
		dimension.setEncodedKey(key);
		dimension.setName(dto.getName());
		dimension.setOwner(dto.getOwner());
		dimension.setParent(dto.getParent() == null ? dto.getEncodedKey() : dto.getParent().getEncodedKey());
		dimension.setPermission(dto.getPermission() == null ? PermissionType.PRIVATE : dto.getPermission());
		dimension.setPosition(dto.getPosition());
		if(dto.getRootDimension() != null)
			dimension.setRootDimension(dto.getRootDimension().getEncodedKey());
		List<eg.backend.domain.Dimension> children = new ArrayList<eg.backend.domain.Dimension>();
		if(dto.getChildren() != null)
			for(Dimension item : dto.getChildren()) {
				children.add(fromDto(item));
			}
		dimension.setChildren(children);
		return dimension;
	}
}
